package cn.com.pajx.pajx_smart_platform.mvp.presenter;

import cn.com.pajx.pajx_smart_platform.mvp.model.CommonModelImpl;
import cn.com.pajx.pajx_smart_platform.mvp.model.IBaseModel;
import cn.com.pajx.pajx_smart_platform.mvp.view.IBaseView;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;
import okhttp3.ResponseBody;

/**
 * Created by ruancw on 2023/04/03.
 * presenter基类
 */

public class BasePresenter implements IBaseModel.IOnRequestListener {
    //view接口
    protected IBaseView mView;
    //model接口实现类
    protected CommonModelImpl mModel;
    //Rxjava中的类
    private CompositeDisposable mCompositeDisposable;

    /**
     * 绑定view
     *
     * @param mView IBaseView
     */
    public void attach(IBaseView mView) {
        this.mView = mView;
        mModel = new CommonModelImpl(this);
    }

    /**
     * 解绑view
     */
    public void detach() {
        if (mView != null) {
            mView = null;
        }
    }

    /**
     * 反注册rxjava
     */
    public void unSubscribe() {
        if (mCompositeDisposable != null) {
            mCompositeDisposable.dispose();
        }
    }

    /**
     * 注册rxjava
     *
     * @param disposable Disposable
     */
    public void addSubscription(Disposable disposable) {//rxjava进行注册
        if (mCompositeDisposable == null) {
            mCompositeDisposable = new CompositeDisposable();
        }
        mCompositeDisposable.add(disposable);
    }

    @Override
    public void onRequestSuccess(String data, String message, int code, String tag) {
        if (mView != null) {
            mView.hideProgress();
            mView.onSuccess(data, message, code, tag);
        }
    }

    @Override
    public void onDownloadSuccess(ResponseBody responseBody, String tag) {

    }

    @Override
    public void onRequestError(String message, int code, String tag) {
        if (mView != null) {
            mView.hideProgress();
            mView.onError(message, code, tag);
        }
    }

    @Override
    public void onRequestFail(Throwable throwable) {
        if (mView != null) {
            mView.hideProgress();
            mView.onFailed(throwable);
        }
    }
}
